package com.mc.mcgoweb.handle;

import com.mc.common.base.BaseResponse;
import com.mc.common.base.ResultEnum;
import com.mc.common.exception.BusinessException;
import com.mc.common.exception.RedisException;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

/**
 * 全局异常捕捉
 */
@ControllerAdvice
public class ExceptionHandle {

    /**
     * 运行时异常捕捉
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    private BaseResponse exceptionHandler(Exception e) {
        BaseResponse response = new BaseResponse();
        response.setCode(String.valueOf(ResultEnum.STATUS_FAILURE.getCode()));
        response.setMessage(e.getMessage());
        return response;
    }

    /**
     * 业务类异常捕捉
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    private BaseResponse businessExceptionHandler(BusinessException e) {
        BaseResponse response = new BaseResponse();
        response.setCode(String.valueOf(e.getErrorCode()));
        response.setMessage(e.getMessage());
        return response;
    }

    /**
     * redis异常捕捉
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RedisException.class)
    @ResponseBody
    private BaseResponse redisExceptionHandler(RedisException e) {
        BaseResponse response = new BaseResponse();
        response.setCode(String.valueOf(e.getErrorCode()));
        response.setMessage(e.getMessage());
        return response;
    }


    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     *
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
    }

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     *
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "Magical Sam");
    }

}
